<template lang="pug">
.part-select
  mt-dialog(
    v-model="model"
    cancel-text="取消"
    size="middle"
    :title="tileName"
    v-bind:onCancel="onCancel"
    v-bind:onConfirm="onConfirm"
    v-bind:onClose="onClose"
  )
    data-page(
      v-bind="pageParams"
    )
      mt-table(
        v-bind="tableProps"
      )
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import type { PartEntity, PartQueryParams } from "@scmt/api-pacs-part";
import type { PacsDevicePartEntity } from "@scmt/api-pacs-device-part";
//添加 Props属性
const props = defineProps({
  selectEquipment: Object,
  selectAction: String,
});
const model = defineModel({
  default: false,
});
//弹框标题
const tileName = ref<null | String>("选择部位");
const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<PartQueryParams>({
  name: "",
  pageNum: 1,
  pageSize: 20,
});
// 调用defineEmits方法 并接受父组件给绑定的事件
const emit = defineEmits(["handeSelect"]);

const editingObj = ref<null | PartEntity>(null);
//选择的id集合
const selectIds = ref<Array<String>>([]);
const isResion = ref(false);
const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    let params = Object.assign(
      { deviceId: props.selectEquipment?.value?.id },
      queryPramas,
      q
    );
    if (!props.selectEquipment || !props.selectEquipment.id) {
      params = Object.assign({ deviceId: "testtt" }, queryPramas, q);
    } else {
      params = Object.assign(
        { deviceId: props.selectEquipment?.id },
        queryPramas,
        q
      );
    }
    if (isResion.value) {
      //需要关联 查询未关联的
      return $api.pacs.part.queryDeviceAndPartCorrelationPageList(params);
    } else {
      //取消关联 查询关联的
      return $api.pacs.part.queryPacsDevicePartListByDeviceId(params);
    }
  },
  save: (model: PartEntity) => {
    return $api.pacs.part.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.pacs.part.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  //批量关联 关联设备部位数据
  batchInsertPacsDevicePart: (item: PacsDevicePartEntity) => {
    return $api.pacs.pacsDevicePart.batchInsertPacsDevicePart(item).then(() => {
      $notify.success("保存成功");
      //传递给父组件
      emit("handeSelect");
      model.value = false;
    });
  },
  //批量取消 关联设备部位数据
  batchDeletePacsDevicePart: (item: PacsDevicePartEntity) => {
    return $api.pacs.pacsDevicePart.batchDeletePacsDevicePart(item).then(() => {
      $notify.success("保存成功");
      //传递给父组件
      emit("handeSelect");
      model.value = false;
    });
  },
});
const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "partName",
      label: "部位名称",
    },
    {
      prop: "partCode",
      label: "部位编码",
    },
  ];

  const headerActions: Action[] = [];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    columns: 3,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      {
        prop: "partName",
        label: "部位名称",
        tooltip: true,
        minWidth: "120px",
      },
      {
        prop: "partCode",
        label: "部位编码",
      },
      {
        prop: "sortNumber",
        label: "排序号",
        tooltip: true,
        minWidth: "120px",
      },
      {
        prop: "pinyinCode",
        label: "拼音码",
        tooltip: true,
        minWidth: "120px",
      },

      {
        prop: "createTime",
        label: "创建时间",
        tooltip: true,
        minWidth: "120px",
        format: "datetime",
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    onSelectionChange: (row: any) => {
      selectIds.value = [];
      for (const key in row) {
        if (Object.prototype.hasOwnProperty.call(row, key)) {
          const element = $api.pacs.part.$$createEntity(row[key]);
          selectIds.value.push(element.id);
        }
      }
    },
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.pacs.part.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
  }
};
//弹框点击确认事件
const onConfirm = () => {
  if (selectIds.value && selectIds.value.length > 0) {
    const modelItem = {
      deviceId: props.selectEquipment?.id, // 设备id
      partIdList: selectIds.value, // 部位id
    };
    const entity = $api.pacs.pacsDevicePart.$$createEntity(modelItem);
    if (isResion.value) {
      request("batchInsertPacsDevicePart", entity);
    } else {
      request("batchDeletePacsDevicePart", entity);
    }
  }
};
//关闭弹框
const onCancel = () => {
  model.value = false;
};
//取消
const onClose = () => {
  model.value = false;
};
watch(
  () => model.value,
  (item) => {
    if (item) {
      tileName.value = "选择部位";
      if ("关联" == props.selectAction) {
        isResion.value = true;
        tileName.value = "批量关联部位";
      } else if ("取消" == props.selectAction) {
        isResion.value = false;
        tileName.value = "批量取消关联部位";
      }
      request("tableData");
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
